<?php if(!defined('PUBLIC_DIR')) die('No Access!');
using('System');

Cnamespace('System');
class Event implements iEvent{
	private static $EventsData = array();
	private static $DBHandler = NULL;
	private $Name = '';

	public function __construct($_name){
		if (!isset(self::$EventsData[$_name])){
			if (self::$DBHandler == NULL)
				self::$DBHandler = Config::GetProvider();
			self::$DBHandler->Query("SELECT handle FROM [Events] WHERE name = '$_name';");
			$data = array_values(self::$DBHandler->FetchArray());
			self::$EventsData[$this->Name] = $data;
			EventHandler::AddEvent($_name, $this);
			//if(count($data) === 0)
				//trigger_error('Event "' . $_name . '" not exits!', E_USER_NOTICE);
		}
		$this->Name = $_name;
	}

	public function AddHandler($_handle, $_permanent = True){
		self::$EventsData[$this->Name][] = $_handle;
		if ($_permanent === True){
			if (self::$DBHandler == NULL)
				self::$DBHandler = Config::GetProvider();
			self::$DBHandler->Query("INSERT INTO [Events] (name, handle) VALUES ('$_name', '$_handle');");
		}
	}

	public function Invoke(array $_params = array()){
		if (isset(self::$EventsData[$this->Name]) && is_array(self::$EventsData[$this->Name]))
		foreach(self::$EventsData[$this->Name] as $id => $handle){
			$action = new Action($handle);
			Dispather::Invoke($action, $_params);
		}
	}
}
